package com.xiaoyi.library.Interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.stereotype.Component;

@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    // 在这里实现拦截器逻辑
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在这里获取用户登录状态并验证
        String userId = (String) request.getSession().getAttribute("userId");
        if (userId == null) {
            // 用户未登录，返回错误信息或重定向至登录页面
            response.setStatus(401);
            response.getWriter().write("未登录");
            //或者重定向至登录页面
            //response.sendRedirect("/login");
            return false; // 拦截请求
        } else {
            // 用户已登录，放行请求
            return true;
        }
    }
}
